<template>
    <div class="video-selector-panel">
      <!-- 保留现有的头部 -->
      <el-card class="panel-card">
        <template #header>
          <div class="card-header">
            <h2>{{ panelTitle }}</h2>
            <el-button
              type="primary"
              size="small"
              @click="refreshVideos"
              :loading="loading"
            >
              刷新列表
            </el-button>
          </div>
        </template>
  
        <el-tabs v-model="activeTab">
          <el-tab-pane label="选择已有视频" name="select">
            <div v-if="loading" class="loading-container">
              <el-skeleton :rows="3" animated />
            </div>
            
            <div v-else-if="videos.length === 0" class="empty-state">
              <el-empty description="暂无可用视频" />
            </div>
            
            <div v-else class="videos-grid">
              <div 
                v-for="video in videos" 
                :key="video.id" 
                class="video-item"
                :class="{ 'selected': selectedVideoId === video.id, 'default': video.id === internalSelectedId }"
              >
                <div class="video-preview" @click="handleVideoSelect(video)">
                  <!-- 视频缩略图 - 修改鼠标悬停逻辑 -->
                  <div class="video-thumbnail" 
                       @mouseenter="hoverVideo(video)" 
                       @mouseleave="unhoverVideo(video)">
                    <video 
                      :ref="el => { if (el) videoRefs[video.id] = el }"
                      :src="getVideoUrl(video)" 
                      muted 
                      preload="metadata" 
                      class="thumbnail-video"
                      :controls="hoveredVideoId === video.id"
                      @loadedmetadata="(e) => handleVideoMetadata(e, video.id)"
                    ></video>
                    
                    <div class="video-duration" v-if="videoDurations[video.id] && hoveredVideoId != video.id">
                      {{ formatDuration(videoDurations[video.id]) }}
                    </div>
                    
                    <!-- 只在未悬停时显示遮罩层 -->
                    <div class="thumbnail-overlay" v-if="hoveredVideoId !== video.id">
                      <el-icon class="play-icon"><video-play /></el-icon>
                    </div>
  
                    <!-- <div class="default-badge" v-if="video.is_default">默认</div> -->
                  </div>
                  
                  <div class="video-info">
                    <div class="video-name" :title="video.filename">
                      {{ truncateText(video.filename, 25) }}
                    </div>
                    <div class="video-date">{{ formatDate(video.created_at) }}</div>
                  </div>
                </div>
                
                <div class="video-actions">
                  <el-radio
                    v-model="internalSelectedId" 
                    :label="video.id"
                  >
                    选择
                  </el-radio>
                  
                  <div class="action-buttons" >
                    <el-tooltip content="设为默认"  placement="top">
                      <el-button style="display: none;"
                        type="primary" 
                        :icon="Star" 
                        circle 
                        size="small"
                        :disabled="video.is_default"
                        @click="setAsDefault(video)"
                      ></el-button>
                    </el-tooltip>
                    
                    <el-tooltip content="删除视频" placement="top">
                      <el-button 
                        type="danger" 
                        :icon="Delete" 
                        circle 
                        size="small"
                        @click="confirmDelete(video)"
                      ></el-button>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <!-- 保留上传标签页内容 -->
          <el-tab-pane label="上传新视频" name="upload">
            <VideoUploader 
              :video-type="videoType"
              @upload-success="handleUploadSuccess"
              @upload-error="handleUploadError"
            />
          </el-tab-pane>
        </el-tabs>
      </el-card>
  
      <!-- 保留删除确认对话框 -->
      <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除"
        width="400px"
      >
        <p>确定要删除视频 "{{ videoToDelete?.filename || '' }}" 吗？</p>
        <p class="warning-text">删除后将无法恢复，且该视频会从所有使用它的地方移除。</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="deleteVideo" :loading="deleting">确定删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { defineComponent, ref, computed, onMounted, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Star, Delete, VideoPlay } from '@element-plus/icons-vue';
  import VideoUploader from '@/components/VideoUploader.vue';
  import introOutroService from '@/services/introOutroService';
  import { genOutsideVideoURL } from '@/utils/videoHelper';
  
  export default defineComponent({
    name: 'VideoSelectorPanel',
    components: {
      VideoUploader
    },
    props: {
      videoType: {
        type: String,
        required: true,
        validator: (value) => ['opening', 'ending', 'mid'].includes(value)
      },
      modelValue: {
        type: [Number, String, null],
        default: null
      },
      title: {
        type: String,
        default: ''
      }
    },
    emits: ['update:modelValue', 'selection-change', 'video-deleted', 'video-set-default'],
    setup(props, { emit }) {
      // 现有的 refs
      const videos = ref([]);
      const loading = ref(false);
      const activeTab = ref('select');
      const videoRefs = ref({});
      const videoDurations = ref({});
      const deleteDialogVisible = ref(false);
      const videoToDelete = ref(null);
      const deleting = ref(false);
      
      // 新增：跟踪当前悬停的视频
      const hoveredVideoId = ref(null);
      
      // 内部选中ID，用于处理默认值
      const internalSelectedId = ref(props.modelValue);
      
      // 监听 modelValue 的变化
      watch(() => props.modelValue, (newVal) => {
        internalSelectedId.value = newVal;
      });
      
      // 监听内部选中的变化
      watch(() => internalSelectedId.value, (newVal) => {
        if (newVal !== props.modelValue) {
          emit('update:modelValue', newVal);
          const selectedVideo = videos.value.find(v => v.id === newVal);
          if (selectedVideo) {
            emit('selection-change', selectedVideo);
          }
        }
      });
      
      // 计算面板标题
      const panelTitle = computed(() => {
        if (props.title) return props.title;
        if (props.videoType === 'opening') return '片头视频选择';
        if (props.videoType === 'ending') return '片尾视频选择';
        if (props.videoType === 'mid') return '中间视频选择';
        return '视频选择';
      });
  
      // 鼠标悬停在视频上
      const hoverVideo = (video) => {
        hoveredVideoId.value = video.id;
        playPreview(video);
      };
      
      // 鼠标离开视频
      const unhoverVideo = (video) => {
        hoveredVideoId.value = null;
        stopPreview(video);
      };
  
      // 加载视频列表
      const loadVideos = async () => {
        loading.value = true;
        try {
          const result = await introOutroService.getIntroOutroVideos(props.videoType);
          if (result.success) {
            videos.value = result.videos || [];
            
            // 设置默认选中项
            // const defaultVideo = videos.value.find(v => v.is_default);
            // if (defaultVideo && !internalSelectedId.value) {
            //   internalSelectedId.value = defaultVideo.id;
            //   emit('update:modelValue', defaultVideo.id);
            //   emit('selection-change', defaultVideo);
            // }
          } else {
            console.error('加载视频列表失败:', result.message);
            ElMessage.error('加载视频列表失败');
          }
        } catch (error) {
          console.error('获取视频列表出错:', error);
          ElMessage.error('获取视频列表出错');
        } finally {
          loading.value = false;
        }
      };
  
      // 刷新视频列表
      const refreshVideos = () => {
        loadVideos();
      };
  
      // 处理视频选择
      const handleVideoSelect = (video) => {
        if (internalSelectedId.value === video.id) {
          internalSelectedId.value = null;
        } else {
          internalSelectedId.value = video.id;
        }
      };
  
      // 播放视频预览
      const playPreview = (video) => {
        const videoElement = videoRefs.value[video.id];
        if (videoElement) {
          videoElement.currentTime = 0;
          
          // 如果已经加载元数据但还没有记录时长，则记录
          if (videoElement.readyState >= 1 && !videoDurations.value[video.id]) {
            videoDurations.value[video.id] = videoElement.duration;
          }
          
          videoElement.play().catch(err => {
            // 静默处理播放失败
            console.warn('视频预览播放失败:', err);
          });
        }
      };
  
      // 停止视频预览
      const stopPreview = (video) => {
        const videoElement = videoRefs.value[video.id];
        if (videoElement && !videoElement.paused) {
          videoElement.pause();
        }
      };
  
      // 处理视频元数据加载
      const handleVideoMetadata = (event, videoId) => {
        const video = event.target;
        if (video && !isNaN(video.duration)) {
          videoDurations.value[videoId] = video.duration;
        }
      };
  
      // 保留其他现有方法...
      const setAsDefault = async (video) => {
        try {
          const result = await introOutroService.setDefaultVideo(video.id, props.videoType);
          if (result.success) {
            ElMessage.success('已设置为默认视频');
            emit('video-set-default', video);
            
            // 更新本地数据列表中的默认标记
            videos.value = videos.value.map(v => ({
              ...v,
              is_default: v.id === video.id
            }));
          } else {
            ElMessage.error(result.message || '设置默认视频失败');
          }
        } catch (error) {
          console.error('设置默认视频失败:', error);
          ElMessage.error('设置默认视频失败');
        }
      };
  
      // 确认删除视频
      const confirmDelete = (video) => {
        videoToDelete.value = video;
        deleteDialogVisible.value = true;
      };
  
      // 删除视频
      const deleteVideo = async () => {
        if (!videoToDelete.value) return;
        
        deleting.value = true;
        try {
          const result = await introOutroService.deleteVideo(videoToDelete.value.id);
          if (result.success) {
            ElMessage.success('视频已删除');
            
            // 如果删除的是当前选中的视频，清除选择
            if (internalSelectedId.value === videoToDelete.value.id) {
              internalSelectedId.value = null;
              emit('update:modelValue', null);
              emit('selection-change', null);
            }
            
            // 从列表中移除
            videos.value = videos.value.filter(v => v.id !== videoToDelete.value.id);
            emit('video-deleted', videoToDelete.value);
            
            deleteDialogVisible.value = false;
            videoToDelete.value = null;
          } else {
            ElMessage.error(result.message || '删除视频失败');
          }
        } catch (error) {
          console.error('删除视频失败:', error);
          ElMessage.error('删除视频失败');
        } finally {
          deleting.value = false;
        }
      };
  
      // 保留其他现有方法...
      const getVideoUrl = (video) => {
        if (video.file_path) {
          return genOutsideVideoURL(video.file_path)
        }
        return ''
      };
  
      // 处理上传成功
      const handleUploadSuccess = (data) => {
        ElMessage.success(`${props.videoType === 'opening' ? '片头' : '片尾'}视频上传成功`);
        activeTab.value = 'select';
        loadVideos(); // 刷新视频列表
        
        // 自动选中新上传的视频
        setTimeout(() => {
          internalSelectedId.value = data.id;
          emit('update:modelValue', data.id);
          
          // 查找上传的视频对象
          const uploadedVideo = videos.value.find(v => v.id === data.id);
          if (uploadedVideo) {
            emit('selection-change', uploadedVideo);
          }
        }, 500);
      };
  
      // 处理上传失败
      const handleUploadError = (error) => {
        ElMessage.error(`上传失败: ${error}`);
      };
  
      // 格式化日期
      const formatDate = (dateString) => {
        if (!dateString) return '未知时间';
        
        try {
          const date = new Date(dateString);
          return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          });
        } catch (e) {
          return dateString;
        }
      };
  
      // 格式化视频时长
      const formatDuration = (seconds) => {
        if (!seconds || isNaN(seconds)) return '00:00';
        
        const mins = Math.floor(seconds / 60);
        const secs = Math.floor(seconds % 60);
        return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
      };
  
      // 截断文本
      const truncateText = (text, maxLength) => {
        if (!text) return '';
        return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
      };
  
      // 监听视频类型变化，重新加载视频列表
      watch(() => props.videoType, () => {
        loadVideos();
      });
  
      // 组件加载时获取视频列表
      onMounted(() => {
        loadVideos();
      });
  
      return {
        videos,
        loading,
        activeTab,
        videoRefs,
        videoDurations,
        internalSelectedId,
        panelTitle,
        deleteDialogVisible,
        videoToDelete,
        deleting,
        hoveredVideoId,
        refreshVideos,
        handleVideoSelect,
        playPreview,
        stopPreview,
        handleVideoMetadata,
        setAsDefault,
        confirmDelete,
        deleteVideo,
        getVideoUrl,
        handleUploadSuccess,
        handleUploadError,
        formatDate,
        formatDuration,
        truncateText,
        hoverVideo,
        unhoverVideo,
        Star,
        Delete,
        VideoPlay
      };
    }
  });
  </script>
  
  <style scoped>
  .panel-card {
    height: 100%;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .card-header h2 {
    margin: 0;
    font-size: 18px;
    color: #303133;
  }
  
  .loading-container, .empty-state {
    padding: 20px 0;
    display: flex;
    justify-content: center;
  }
  
  .videos-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 16px;
    margin-bottom: 16px;
  }
  
  .video-item {
    border-radius: 8px;
    border: 1px solid #EBEEF5;
    overflow: hidden;
    transition: all 0.3s;
    background-color: #fff;
  }
  
  .video-item:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
  
  .video-item.selected {
    border-color: #409EFF;
    background-color: #ecf5ff;
  }
  
  .video-item.default {
    border-color: #67C23A;
  }
  
  .video-preview {
    cursor: pointer;
  }
  
  .video-thumbnail {
    position: relative;
    width: 100%;
    height: 124px;
    background-color: #000;
    overflow: hidden;
  }
  
  .thumbnail-video {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  /* 修改遮罩层样式，确保在非悬停时可见 */
  .thumbnail-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 1; /* 默认可见 */
    transition: opacity 0.3s;
  }
  
  .play-icon {
    font-size: 48px;
    color: #fff;
    filter: drop-shadow(0 0 5px rgba(0, 0, 0, 0.5));
  }
  
  .video-duration {
    position: absolute;
    bottom: 8px;
    right: 8px;
    background-color: rgba(0, 0, 0, 0.7);
    color: #fff;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 12px;
    z-index: 2; /* 确保显示在控件上方 */
  }
  
  .default-badge {
    position: absolute;
    top: 8px;
    right: 8px;
    background-color: #67C23A;
    color: #fff;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    z-index: 2; /* 确保显示在控件上方 */
  }
  
  .video-info {
    padding: 10px;
  }
  
  .video-name {
    font-size: 14px;
    font-weight: 500;
    line-height: 1.4;
    margin-bottom: 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .video-date {
    font-size: 12px;
    color: #909399;
  }
  
  .video-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 10px;
    border-top: 1px solid #EBEEF5;
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
  }
  
  .warning-text {
    color: #F56C6C;
    font-size: 14px;
  }
  
  /* 确保视频控件的样式 */
  .thumbnail-video::-webkit-media-controls {
    opacity: 0;
    transition: opacity 0.3s;
  }
  
  .thumbnail-video:hover::-webkit-media-controls {
    opacity: 1;
  }
  
  /* 自定义视频控件颜色 */
  .thumbnail-video::-webkit-media-controls-panel {
    background-color: rgba(0, 0, 0, 0.5);
  }
  </style>